import axios from 'axios';
import JSEncrypt from 'jsencrypt';

import { showToast } from 'vant'
import { useUserStore } from '@/stores'
import router from '@/router'


const publicKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlpdP6dmLEmINgQq5l7Lc
QgUGWvfQXfTmY7TqE0qHyimA3l/mb8N8aWCTjmXTgfnF6Hz1qf42rvBbR9/Xa/Q5
pZ5Ul9NaHCxc7ded6V2Kuak5it00iNpYlAhZF32iOr1Tral59nk7fAasPBC3KkSv
yF2xatRF6BOcSyV+9+Mh2oumor2uq8pmNcw8ngEDQkgbRXfoeALVKIayLXZdVVNv
FLl44c43uLUTxcK301B/QelaZO+d7rbgDAWQwCOaijbehxNScTD88lmh+0AWoGXf
+lSUnyUxbeoAtxVlH7eU6R4ged6CHVwRKOMjNGPBH5mC3Wigv1ASvKSrZGk3kF2O
FwIDAQAB
-----END PUBLIC KEY-----`;


const http = axios.create({
  baseURL: 'http://api.English.cn:8000/',
  timeout: 5000,
});


// 请求��截器
http.interceptors.request.use(
  (config) => {
    const store = useUserStore()

    // 对数据进行加密
    if (config.data) {
      const encrypt = new JSEncrypt();
      encrypt.setPublicKey(publicKey);
      const encryptedData = encrypt.encrypt(JSON.stringify(config.data));

      if (encryptedData) {
        config.data = encryptedData;
      } else {
        console.error('Encryption failed');
      }
    }

    // 检查是否需要添加 token
    const token = store.token
    const url = config.url
    if ( url && url.indexOf('tok=true') !== -1) {
      if (!token) {
        router.push('/login')
        // 如果没有 token，抛出错误
        return Promise.reject(new Error('请先登录'));
      }
      config.headers['Authorization'] = `Bearer ${token}`;
    }

    return config;
  },
  (error) => {

    // 对请求错误做些什么
    return Promise.reject(error);
  }
)



// 添加响应拦截器
http.interceptors.response.use(
  (response) => {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response;
  },
  (error) => {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    if (error?.response?.status === 500) {
      showToast({
        message: '登录过期，请重新登录',
        duration: 1500,
      })
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

 // export default http;
export const request = <T>(
  url: string,
  method: string,
  data?: object,         //问号表示可选
  tok?: boolean
) => {
  const config = {
    url: url,
    method: method,
    [method.toLowerCase()==='get'? 'params': 'data']: data,
  }
  if (tok) {
    config.url = config.url + '?tok=true'
  }
  return http.request<T>({ ...config})
}
